Lesson 7 | Reading streams |
Objective | Create reader streams that read data |
Reading Writing Streams
You have learned that the primary method used to read from a stream is read()
, which is defined in both the InputStream
class and the Reader
class, as well as all subclasses of those two classes. There are various overloaded versions of read()
throughout these classes that read data in different ways.
Following is an example of reading and displaying characters from a string using a buffered string reader:
BufferedReader in = new BufferedReader (new StringReader(str));
int c;
while ((c = in.read()) != -1)
System.out.print((char)c);
read() method
In this example, the read()
method is used to read each character from a string until the end of the string is reached, in which case read()
will return -1.
The System.in
standard input object is an InputStream
object, so you can read from standard input using the read()
method on the System.in
object.
What are the overloaded versions of the read() method in InputStream and Reader class?
The InputStream and Reader classes in Java provide overloaded versions of the read() method to allow for different ways of reading data from an input source.
In the InputStream class:
- public int read(): This method reads a single byte of data from the input stream and returns it as an integer in the range of 0 to 255.
- public int read(byte[] b): This method reads b.length bytes of data from the input stream and stores them in the byte array b. It returns the number of bytes actually read, or -1 if the end of the stream has been reached.
- public int read(byte[] b, int off, int len): This method reads up to len bytes of data from the input stream and stores them in the byte array b, starting at the off position. It returns the number of bytes actually read, or -1 if the end of the stream has been reached.
In the Reader class:
- public int read(): This method reads a single character of data from the input stream and returns it as an integer, or -1 if the end of the stream has been reached.
- public int read(char[] cbuf): This method reads characters from the input stream and stores them in the character array cbuf. It returns the number of characters actually read, or -1 if the end of the stream has been reached.
- public int read(char[] cbuf, int off, int len): This method reads up to len characters from the input stream and stores them in the character array cbuf, starting at the off position. It returns the number of characters actually read, or -1 if the end of the stream has been reached.
These overloaded versions of the read() method provide different ways of reading data from an input source, depending on the needs of the application and the specific requirements of the input source.
Reading File - Exercise
In this exercise, you will write an application that counts the number of characters in a file and then displays the count.
Reading File - Exercise